import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { useMutation, gql } from '@apollo/client';

import notification from '@kuiper-components/notification';
import Button from '@kuiper-components/button';
import Tooltip from '@kuiper-components/tooltip';

import s from './style.module.css';

const IGORE_WARN = gql`
	mutation($taskId: MongoID!, $warnIds: [String]!) {
		ignoreWarn(taskId: $taskId, warnIds: $warnIds) {
			_id
			result {
				warnings {
					_id
					id
					level
					title
					detail
					ignoredTime
				}
			}
		}
	}
`;

const CHANGE_TASK_WARN_RESOLVE_STATE = gql`
	mutation($taskId: MongoID!, $warnIds: [String]!, $isResolved: Boolean!) {
		TaskWarnResolveState(
			taskId: $taskId
			warnIds: $warnIds
			isResolved: $isResolved
		) {
			_id
			result {
				warnings {
					_id
					id
					level
					title
					detail
					isResolved
					ignoredTime
				}
			}
		}
	}
`;

function WarningsStatusEdit({
	className,
	idsObj,
	isBatchSetting,
	taskId,
	refetch,
	reset,
	afterActionSuccessful,
	getTooltipContainer,
	controlText,
}) {
	const [tooltipKey, setTooltipKey] = React.useState(idsObj);
	const [igoreWarning] = useMutation(IGORE_WARN);
	const [changeTaskWarnResolveState] = useMutation(
		CHANGE_TASK_WARN_RESOLVE_STATE
	);
	const ids = Object.entries(idsObj)
		.filter(([id, status]) => status)
		.map(([id, x]) => id);
	const handleIgoreWarning = () => {
		igoreWarning({
			variables: {
				taskId,
				warnIds: ids,
			},
		})
			.then(() => {
				notification.success({
					placement: 'top',
					message: `${isBatchSetting ? '批量' : ''}标记为已忽略成功`,
				});
				refetch();
				reset();
				afterActionSuccessful();
				setTooltipKey(Math.random() * 100000);
			})
			.catch(error => {
				notification.error({
					placement: 'top',
					message: `${isBatchSetting ? '批量' : ''}标记为已忽略失败`,
					description: error.message,
				});
			});
	};

	const handleMarkTaskWarnResolve = () => {
		changeTaskWarnResolveState({
			variables: {
				taskId,
				warnIds: ids,
				isResolved: true,
			},
		})
			.then(() => {
				notification.success({
					placement: 'top',
					message: `${isBatchSetting ? '批量' : ''}标记为已${controlText}成功`,
				});
				refetch();
				reset();
				afterActionSuccessful();
				setTooltipKey(Math.random() * 100000);
			})
			.catch(error => {
				notification.error({
					placement: 'top',
					message: `${isBatchSetting ? '批量' : ''}标记为已${controlText}失败`,
					description: error.message,
				});
			});
	};

	const handleMarkWarnUnresolve = () => {
		changeTaskWarnResolveState({
			variables: {
				taskId,
				warnIds: ids,
				isResolved: false,
			},
		})
			.then(() => {
				notification.success({
					placement: 'top',
					message: `${isBatchSetting ? '批量' : ''}标记为待${controlText}成功`,
				});
				refetch();
				reset();
				afterActionSuccessful();
				setTooltipKey(Math.random() * 100000);
			})
			.catch(error => {
				notification.error({
					placement: 'top',
					message: `${isBatchSetting ? '批量' : ''}标记为待${controlText}失败`,
					description: error.message,
				});
			});
	};

	return (
		<Tooltip
			key={tooltipKey}
			trigger="click"
			placement="bottom"
			getTooltipContainer={getTooltipContainer}
			overlayClassName={s.overlay}
			overlay={
				<div className={s.content}>
					<div className={s.li} onClick={handleMarkWarnUnresolve}>
						待{controlText}
					</div>
					<div className={s.li} onClick={handleMarkTaskWarnResolve}>
						已{controlText}
					</div>
					<div className={s.li} onClick={handleIgoreWarning}>
						已忽略
					</div>
				</div>
			}
		>
			{isBatchSetting ? (
				<Button
					className={cn(s.btn, className)}
					link
					primary
					disabled={ids.length === 0}
				>
					批量设置
				</Button>
			) : (
				<svg
					className={cn(className, s.editIcon)}
					width="18"
					height="18"
					viewBox="0 0 18 18"
					fill="none"
					xmlns="http://www.w3.org/2000/svg"
					xlink="http://www.w3.org/1999/xlink"
				>
					<rect width="18" height="18" fill="url(#pattern0)" />
					<defs>
						<pattern
							id="pattern0"
							patternContentUnits="objectBoundingBox"
							width="1"
							height="1"
						>
							<use href="#image0" transform="scale(0.03125)" />
						</pattern>
						<image
							id="image0"
							width="32"
							height="32"
							href=""
						/>
					</defs>
				</svg>
			)}
		</Tooltip>
	);
}

WarningsStatusEdit.propTypes = {
	className: PropTypes.string,
	isBatchSetting: PropTypes.bool,
	idsObj: PropTypes.object,
	refetch: PropTypes.func,
	reset: PropTypes.func,
	afterActionSuccessful: PropTypes.func,
	taskId: PropTypes.string.isRequired,
	getTooltipContainer: PropTypes.func,
	controlText: PropTypes.string,
};
WarningsStatusEdit.defaultProps = {
	className: '',
	isBatchSetting: false,
	idsObj: {},
	refetch: () => {},
	reset: () => {},
	afterActionSuccessful: () => {},
	getTooltipContainer: () => document.body,
	controlText: '修复',
};

export default WarningsStatusEdit;
